package com.zzyl.nursing.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.Period;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 入住Service业务层处理
 *
 * @author zhq
 * @date 2025-08-11
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 入住办理
     *
     * @param checkInApplyDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {

        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        String idCardNo = checkInElderDto.getIdCardNo();
        Long bedId = checkInConfigDto.getBedId();
        // 1.校验老人是否已入住
        LambdaQueryWrapper<Elder> elderWrapper = new LambdaQueryWrapper<>();
        elderWrapper.eq(Elder::getIdCardNo, idCardNo)
                .in(Elder::getStatus, 1, 2, 4);
        Elder elder = elderMapper.selectOne(elderWrapper);
        // 1.1 已入住，结束流程，提示：老人已入住
        if(!Objects.isNull(elder)) {
            throw new BaseException("老人已入住");
        }
        // 2.更新床位状态
        Bed bed = bedMapper.selectById(bedId);
        bed.setBedStatus(1);
        // update bed set bed_status = 1 where id = #{bedId} and bed_status = 0;
        int row = bedMapper.updateEnableStatusById(bed.getBedStatus(), bedId);
        if(row <= 0) {
            throw new BaseException("老人入住，修改床位状态失败");
        }
        // 3.新增或更新老人
        elder = insertOrUpdateElder(checkInElderDto, bed);
        // 4.新增签约办理
        insertContract(elder, checkInConfigDto, checkInContractDto);
        // 5.新增入住信息
        CheckIn checkIn = insertCheckIn(elder, checkInConfigDto, elderFamilyDtoList);
        // 6.新增入住配置信息
        insertCheckInConfig(checkIn, checkInConfigDto);
    }

    @Override
    public CheckInDetailVo getDetailInfo(Long id) {
        //1.查询入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        Long elderId = checkIn.getElderId();
        //2.查询老人信息
        Elder elder = elderMapper.selectElderById(elderId);
        //3.查询合同
        LambdaQueryWrapper<Contract> contractWrapper=new LambdaQueryWrapper<>();
        contractWrapper.eq(Contract::getElderId,elderId);
        contractWrapper.orderByDesc(Contract::getEndDate);
        contractWrapper.last("limit 1");
        Contract contract = contractMapper.selectOne(contractWrapper);
        //4.查询入住配置
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, id));
        //5.转换家属列表
        String remark = checkIn.getRemark();
        List<ElderFamilyVo> list= JSON.parseArray(remark,ElderFamilyVo.class);
        //6.整合数据返回
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //6.1设置入住老人信息
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        Period period=Period.between(LocalDate.parse(elder.getBirthday()),LocalDate.now());
        int age = period.getYears();
        checkInElderVo.setAge(age);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //6.2设置老人家人信息
        checkInDetailVo.setElderFamilyVoList(list);
        //6.3入住配置信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //6.4合同信息
        checkInDetailVo.setContract(contract);

        return checkInDetailVo;

    }

    /**
     * 新增入住配置信息
     * @param checkIn
     * @param checkInConfigDto
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param elder
     * @param checkInConfigDto
     */
    private CheckIn insertCheckIn(Elder elder, CheckInConfigDto checkInConfigDto, List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(elder, checkIn, "id");
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约办理
     * @param elder
     * @param checkInConfigDto
     * @param checkInContractDto
     */
    private void insertContract(Elder elder, CheckInConfigDto checkInConfigDto, CheckInContractDto checkInContractDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInContractDto, contract);
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(0);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人
     * @param checkInElderDto
     * @param bed
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        // 准备老人的数据
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        LambdaQueryWrapper<Elder> elderWrapper = new LambdaQueryWrapper<>();
        elderWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        Elder elderDb = elderMapper.selectOne(elderWrapper);
        if(Objects.isNull(elderDb)) {
            // 新增
            elderMapper.insert(elder);
        } else {
            // 更新
            elder.setId(elderDb.getId());
            elderMapper.updateById(elder);
        }
        return elder;
    }
}
